collections.defaultdict([default\_factory[, ...]]) return dictionary like object but with some subtle differences. It is a dictionary with a default value for keys, so that keys for which no value has been explicitly defined can be accessed without errors (explicitly KeyError). For example


In [ ]:
foo_dict = {'foo_key': 'foo_value', 'bar_key': 'bar_value'}
#accessing key-value pair not present in dictionary would raise KeyError
print foo_dict['foo_bar_key']

In [ ]:
from collections import defaultdict

foo_dict = defaultdict(str)
foo_dict['foo_key'] = 'foo_value'
foo_dict['bar_key'] = 'bar_value'
#Instead of raising KeyError it would be returning an empty string
print foo_dict['foo_bar_key']

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists. For example:


In [ ]:
location_list = [('India', 'Mumbai'), ('US', 'New York'), ('India', 'New Delhi'), ('US', 'Chicago')]
location_dict = defaultdict(list)
for country, place in location_list:
    location_dict[country].append(place)
print location_dict.items()

When each country is encountered for the first time, an empty list is created for it. The list.append() function then appends the place to the empty list. And when the country is encountered again the look-up proceeds normally appending another element to the list.

Assignment Time

Using the concept studied till now, write a code to calculate the number of occurences of each alphabet present in the word "malayalam" ?


In [ ]: